from flask import Blueprint, render_template, request, jsonify
# 暂时注释掉 login_required
# from flask_login import login_required, current_user
from app.data_collection.crawler import WebCrawler
from app.data_processing.sentiment_analyzer import SentimentAnalyzer
import os

# 创建蓝图对象
main = Blueprint('main', __name__)
crawler = WebCrawler()
analyzer = SentimentAnalyzer(api_key=os.getenv('OPENAI_API_KEY'))

# 移除与views.py冲突的路由
# @main.route('/')
# def index():
#     return render_template('index.html')

# @main.route('/dashboard')
# # 暂时注释掉登录要求
# # @login_required
# def dashboard():
#     # 添加一些示例数据
#     stats = {
#         'total_articles': 395000,
#         'today_analysis': 25450,
#         'total_users': 13256,
#         'alerts': 35
#     }
#     recent_analysis = []
#     return render_template('dashboard.html', stats=stats, recent_analysis=recent_analysis)

@main.route('/info-management')
# @login_required
def info_management():
    return render_template('info_management.html')

@main.route('/monitoring-plan')
# @login_required
def monitoring_plan():
    return render_template('monitoring_plan.html')

@main.route('/content-analysis')
# @login_required
def content_analysis():
    return render_template('content_analysis.html')

@main.route('/alert-management')
# @login_required
def alert_management():
    return render_template('alert_management.html')

@main.route('/event-analysis')
# @login_required
def event_analysis():
    return render_template('event_analysis.html')

@main.route('/api/analyze', methods=['POST'])
def analyze():
    data = request.get_json()
    text = data.get('text', '')
    
    if not text:
        return jsonify({'error': '文本不能为空'}), 400
        
    sentiment = analyzer.analyze(text)
    keywords = analyzer.extract_keywords(text)
    
    return jsonify({
        'sentiment': sentiment,
        'keywords': keywords
    })

@main.route('/api/crawl', methods=['POST'])
def crawl():
    data = request.get_json()
    url = data.get('url', '')
    
    if not url:
        return jsonify({'error': 'URL不能为空'}), 400
        
    news_items = crawler.fetch_news(url)
    return jsonify({'news': news_items})

@main.route('/api/stats')
# @login_required
def get_stats():
    # 返回统计数据的API
    return {
        'status': 'success',
        'data': {
            'total_articles': 395000,
            'today_analysis': 25450,
            'total_users': 13256,
            'alerts': 35
        }
    } 